package org.real.guetshop.websocket;

import jakarta.annotation.Resource;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.real.guetshop.context.BaseContext;
import org.real.guetshop.mapper.UserMapper;
import org.real.guetshop.pojo.entity.User;
import org.springframework.stereotype.Component;

@Getter
@Slf4j
@Component
@ServerEndpoint("/WebSocket")
public class WebSocketServer {

    @Resource
    UserMapper userMapper;

    private Session session;

    @SneakyThrows
    @OnOpen
    public void onOpen(Session session) {
        Integer userId = BaseContext.getCurrentId();

        //对用户ID值进行校验
        if(isValidUser(userId)){
            this.session = session;
            WebSocketManager.sentToUser(session, "WebSocket is connected!");
            WebSocketManager.addWebSocketServer(this,userId);
            log.info("与SessionId：{}建立连接，用户ID：{}", session.getId(),userId);
        }else {
            session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,"无效的用户ID"));
        }
    }

    @OnClose
    public void onClose() {
        WebSocketManager.removeWebSocketServer(this);
        log.info("WebSocket连接关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自SessionId:{}的消息:{}", session.getId(), message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Session:{}的WebSocket发生错误", session.getId(), error);
    }

    public String getSessionId() {
        return session.getId();
    }

    /**
     * 校验用户id
     * @param userId
     * @return
     */
    private boolean isValidUser(Integer userId) {
        User user = userMapper.getUserById(userId);
        return user != null;
    }

    public void sendMessage(String msg) {
    }
}
